package com.softeem.cms.service.impl;

import cn.hutool.core.util.RandomUtil;
import cn.hutool.crypto.SecureUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.softeem.cms.dto.R;
import com.softeem.cms.entity.User;
import com.softeem.cms.mapper.UserMapper;
import com.softeem.cms.service.IUserService;
import org.springframework.stereotype.Service;

import java.util.Objects;

/**
 * 用户功能实现的业务层
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService {

    @Override
    public R userLogin(User user) {
        //根据用户名查询
        User user1 = getBaseMapper().selectByUsername(user.getUsername());
        //判断用户是否存在
        if(Objects.isNull(user1)){
            return R.fail().setMsg("该用户不存在");
        }
        //获取用户提交的密码和随机盐并组合加密
        String pwd = SecureUtil.md5(user.getPassword() + user1.getSalt());
        if(Objects.equals(pwd,user1.getPassword())){
            return R.ok().setMsg("登录成功").setData(user1);
        }
        return R.fail().setMsg("密码错误");
    }

    @Override
    public R addUser(User user) {
        //检查当前用户是否存在
        User u1 = getBaseMapper().selectByUsername(user.getUsername());
        if(Objects.nonNull(u1)){
            return R.fail().setMsg("该用户已存在").setCode(1);
        }
        //生成长度为6位的随机字符串作为盐值
        String salt = RandomUtil.randomString(6);
        //使用密码+盐组合加密
        String pwd = SecureUtil.md5(user.getPassword() + salt);
        //为用户对象填充数据
        user.setPassword(pwd);
        user.setSalt(salt);
        //执行添加操作（持久化）
        int i = getBaseMapper().insert(user);
        if(i > 0){
            return R.ok().setMsg("注册成功").setData(user);
        }
        return R.fail().setMsg("注册失败");
    }
}
